﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Xml;
using System.Runtime.Serialization;

namespace NMigrate
{
	public class JsonConfiguration<T> : Configuration<T> where T : class
	{
		string _File;
		public JsonConfiguration(string file)
		{
			if(file == null)
				throw new ArgumentNullException("file");
			_File = file;
		}


		T _Object;
		bool _Initialized;
		public override T GetValue()
		{
			EnsureInitialized();
			return _Object;
		}

		private void EnsureInitialized()
		{
			if(!_Initialized)
			{
				_Initialized = true;
				DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
				MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(File.ReadAllText(_File)));

				var reader = JsonReaderWriterFactory.CreateJsonReader(ms, new XmlDictionaryReaderQuotas());
				_Object = (T)serializer.ReadObject(reader, false);

			}
		}
	}
}
